package com.turing.post.salesmanage.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import com.turing.post.cardmanagement.util.ActivateCard;
import com.turing.post.cardmanagement.util.ActivateCardDao;
import com.turing.post.cardmanagement.util.CardStock;
import com.turing.post.cardmanagement.util.CardStockDao;
import com.turing.post.salesmanage.util.SaleOrder;
import com.turing.post.salesmanage.util.SaleOrderCardDetail;
import com.turing.post.salesmanage.util.SaleOrderCardDetailBusiness;
import com.turing.post.salesmanage.util.SaleOrderCardDetailDao;
import com.turing.post.salesmanage.util.SaleOrderDao;
import com.turing.post.salesmanage.util.SalesManageApplicationException;
import com.turing.post.salesmanage.util.SalesManageRespCode;
import com.turing.post.util.PCPSApplicationException;

/**
 * 销售单售卡明细
 * 
 * @author zxp
 * @Dec 23, 2012
 */
@Stateless(mappedName = "salesmanage.impl.SaleOrderCardDetailBusinessImpl")
@Remote
@Local
public class SaleOrderCardDetailBusinessImpl implements
		SaleOrderCardDetailBusiness {

	@EJB(mappedName = "salesmanage.impl.SaleOrderCardDetailDaoImpl")
	private SaleOrderCardDetailDao saleOrderCardDetailDaoImpl;

	@EJB(mappedName = "salesmanage.impl.SaleOrderDaoImpl")
	private SaleOrderDao saleOrderDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.CardStockDaoImpl")
	private CardStockDao cardStockDaoImpl;

//	@EJB(mappedName = "cardmanagement.impl.MakeCardControlDaoImpl")
//	private MakeCardControlDao makeCardControlDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.ActivateCardDaoImpl")
	private ActivateCardDao activateCardDaoImpl;

	/**
	 * 异常抛出方法
	 * 
	 * @param error
	 * @throws PCPSApplicationException
	 */
	private void errException(String error) throws PCPSApplicationException {
		throw new SalesManageApplicationException(
				SalesManageApplicationException.ERRCODE_CATEGORY_APPLICATION,
				SalesManageRespCode.SALESBUSINESS_ARGS_NULL, error);
	}

	@Override
	public void deleteSaleOrderCardDetailInfo(
			SaleOrderCardDetail saleOrderCardDetail)
			throws PCPSApplicationException {
		SaleOrderCardDetail socd = saleOrderCardDetailDaoImpl
				.getSaleOrderCardDetailByPrimaryKey(saleOrderCardDetail);
		if (socd == null) {
			errException("销售单售卡明细未查询到!");
		} else {
			// 查询销售单是否存在录入售卡明细时判断销售单状态,只有录入状态才可添加
			SaleOrder saleOrder = saleOrderDaoImpl
					.getSaleOrderForUpdate(saleOrderCardDetail.getSaleOrderId());
			// 判断状态
			if (!saleOrder.getOrderStatus().equals(
					SaleOrder.SALEORDER_ORDERSTATUS_INPUT)) {
				errException("只允许在录入状态下删除售卡明细!");
			}
			// 删除
			Integer deletecount = saleOrderCardDetailDaoImpl
					.deleteSaleOrderCardDetail(socd);
			if (deletecount >= 0) {
				// 更新销售单SaleOrder内金额和卡张数
				saleOrder.setTotalCardCount(saleOrder.getTotalCardCount()
						- socd.getCardCount());
				saleOrder.setTotalSaleAmount(saleOrder.getTotalSaleAmount()
						.subtract(socd.getOrderLineTotal()));
				saleOrderDaoImpl.updateSaleOrder(saleOrder);
			} else {
				errException("删除失败，查询传入参数是否正确!");
			}
		}
	}

//	@Override
//	public void insertSaleOrderCardDetailInfo(
//			SaleOrderCardDetail saleOrderCardDetail)
//			throws PCPSApplicationException {
//		// 对象为null
//		if (saleOrderCardDetail == null) {
//			errException("传入售卡明细对象为空!");
//		}
//		// 销售单编号
//		if (saleOrderCardDetail.getSaleOrderId() == null) {
//			errException("销售单编号为空!");
//		}
//		// 查询销售单是否存在录入售卡明细时判断销售单状态,只有录入状态才可添加
//		SaleOrder saleOrder = saleOrderDaoImpl
//				.getSaleOrderForUpdate(saleOrderCardDetail.getSaleOrderId());
//		if (saleOrder == null) {
//			errException("所用销售单不存在!");
//		}
//		// 判断状态
//		if (!saleOrder.getOrderStatus().equals(
//				SaleOrder.SALEORDER_ORDERSTATUS_INPUT)) {
//			errException("只允许在录入状态下添加售卡明细!");
//		}
//		// 批次号
//		// if (PCPSUtil.isEmpty(saleOrderCardDetail.getBatchNo())) {
//		// errException("批次号为空!");
//		// }
//		// 起始顺序号
//		if (PCPSUtil.isEmpty(saleOrderCardDetail.getStartCardSeqNo())) {
//			errException("起始顺序号为空!");
//		}
//		// 结束顺序号
//		if (PCPSUtil.isEmpty(saleOrderCardDetail.getEndCardSeqNo())) {
//			errException("结束顺序号为空!");
//		}
//		// 自动截取卡顺序号
//		if (saleOrderCardDetail.getStartCardSeqNo().trim().length() < 18) {
//			String batchNo = saleOrderCardDetail.getStartCardSeqNo().substring(
//					0, 6);
//			if (!batchNo.equals(saleOrderCardDetail.getEndCardSeqNo()
//					.substring(0, 6))) {
//				errException("录入的卡顺序号不为同一批次的卡!");
//			} else {
//				saleOrderCardDetail.setBatchNo(PCPSUtil.getICNoByBranchNo(saleOrder.getSaleBranchNo())+batchNo);
//			}
//		} else {
//			String batchNo = saleOrderCardDetail.getStartCardSeqNo().substring(
//					0, 12);
//			if (!batchNo.equals(saleOrderCardDetail.getEndCardSeqNo()
//					.substring(0, 12))) {
//				errException("录入的卡顺序号不为同一批次的卡!");
//			} else {
//				saleOrderCardDetail.setBatchNo(batchNo);
//			}
//		}
//		// // 起始卡号
//		// if (PCPSUtil.isEmpty(saleOrderCardDetail.getStartCardNo())) {
//		// errException("起始卡号为空!");
//		// }
//		// // 结束卡号
//		// if (PCPSUtil.isEmpty(saleOrderCardDetail.getEndCardNo())) {
//		// errException("结束卡号为空!");
//		// }
//		// 判断是否添加
//		if (saleOrderCardDetailDaoImpl
//				.getSaleOrderCardDetailByPrimaryKey(saleOrderCardDetail) != null) {
//			errException("添加的销售单卡绑定已经存在!");
//		}
//		// 根据顺序号计算的卡张数
//		Integer cardCount = 0;
//		try {
//			cardCount = Integer.parseInt(saleOrderCardDetail.getEndCardSeqNo()
//					.substring(12, 18))
//					- Integer.parseInt(saleOrderCardDetail.getStartCardSeqNo()
//							.substring(12, 18));
//			cardCount = cardCount + 1;
//			
//		} catch (Exception e) {
//			errException("卡号段" + saleOrderCardDetail.getStartCardSeqNo() + "到"
//					+ saleOrderCardDetail.getEndCardSeqNo() + "输入错误!");
//		}
//		// 卡张数
//		if (saleOrderCardDetail.getCardCount() == null
//				|| !saleOrderCardDetail.getCardCount().equals(cardCount)) {
//			errException("售卡张数为空或数量错误!");
//		}
//		List<CardStock> cardStockList = cardStockDaoImpl
//				.getCardStockListBySaleBranchNoAndStatusAndCredseqno(
//						saleOrderCardDetail.getStartCardSeqNo(),
//						saleOrderCardDetail.getEndCardSeqNo(),
//						CardStock.CARDSTOCK_STATUS_NORMAL, saleOrder
//								.getSaleBranchNo());
//		HashMap<String, String> mp = new HashMap<String, String>();
//		for (CardStock cs : cardStockList) {
//			mp.put(cs.getSaleBranchNo(), cs.getSaleBranchNo());
//		}
//		if (mp.size() > 1) {
//			errException("添加的卡归属销售机构不唯一!");
//		}
//		// 验证输入卡号是否连续，且状态正常
//		if (saleOrderCardDetail.getCardCount() != cardStockList.size()) {
//			errException("卡号段" + saleOrderCardDetail.getStartCardSeqNo() + "到"
//					+ saleOrderCardDetail.getEndCardSeqNo() + "有误，不连续或状态异常!");
//		}
//		// 归属机构判断
//		if (!saleOrder.getSaleBranchNo().equals(
//				cardStockList.get(0).getSaleBranchNo())) {
//			errException("添加的卡不为该销售机构的卡!");
//		}
//		// 判断 初始卡内金额
//		MakeCardControl mcc = makeCardControlDaoImpl
//				.getMakeCardControlByBatchNo(saleOrderCardDetail.getBatchNo());
//		if (mcc == null) {
//			errException("批次号输入错误，未能找到制卡信息!");
//		}
//		// 卡面值
//		CardParValue cpv = null;// cardParValueDaoImpl
//		// .getCardParValueByCardParValueId(mcc.getCardParValueId());
//		if (cpv.getCardParValue().compareTo(0) == 0) {
//			// 卡面值为0，前台输入
//			if (saleOrderCardDetail.getInitDeposit().compareTo(0) <= 0) {
//				errException("卡面值为0，请填写售卡金额!");
//			}
//		} else {
//			if (saleOrderCardDetail.getInitDeposit().compareTo(0) != 0) {
//				if (saleOrderCardDetail.getInitDeposit().compareTo(
//						cpv.getCardParValue()) == 0) {
//					errException("卡面值输入错误，如不清楚填写0!");
//				}
//			}
//			// 设置默认卡面值
//			saleOrderCardDetail.setInitDeposit(cpv.getCardParValue());
//		}
//		// 计算行内金额
//		try {
//			// 面值*张数，转为分
//			saleOrderCardDetail
//					.setOrderLineTotal(new BigInteger(
//							String.valueOf((saleOrderCardDetail
//									.getInitDeposit() * saleOrderCardDetail
//									.getCardCount()))));
//		} catch (Exception e) {
//			errException("行内金额合计计算失败，参数输入错误!");
//		}
//		saleOrderCardDetailDaoImpl
//				.insertSaleOrderCardDetail(saleOrderCardDetail);
//		// 更新销售单SaleOrder内金额和卡张数
//		saleOrder.setTotalCardCount(saleOrder.getTotalCardCount()
//				+ saleOrderCardDetail.getCardCount());
//		saleOrder.setTotalSaleAmount(saleOrder.getTotalSaleAmount().add(
//				saleOrderCardDetail.getOrderLineTotal()));
//		saleOrderDaoImpl.updateSaleOrder(saleOrder);
//	}

	// 销售单所销售卡库存列表，用于自动产生实名excel使用
	@Override
	public List<CardStock> getCardStockListBySaleOrderId(BigInteger saleOrderId) {
		// 销售单
		SaleOrder saleOrder = saleOrderDaoImpl
				.getSaleOrderBySaleOrderId(saleOrderId);
		// 销售卡详细信息
		HashMap<String, String> hm = new HashMap<String, String>();
		HashMap<String, String> batchNoHm = new HashMap<String, String>();
		// 售卡明细，合计售卡张数和金额
		List<SaleOrderCardDetail> saleOrderCardDetailList = saleOrderCardDetailDaoImpl
				.getSaleOrderCardDetailListBySaleOrderId(saleOrder
						.getSaleOrderId());
		SaleOrderCardDetail socd = null;
		CardStock cs = null;
		ActivateCard ac = null;
		List<String> cardSeqNoList = new ArrayList<String>();
		// 销售单售卡明细
		for (int i = 0; i < saleOrderCardDetailList.size(); i++) {
			socd = saleOrderCardDetailList.get(i);
			// 销售单状态，已激活去activecard中查询数据
			if (saleOrder.getOrderStatus().equals(
					SaleOrder.SALEORDER_ORDERSTATUS_ACTIVATED)) {
				List<ActivateCard> ActivateCardList = activateCardDaoImpl
						.getActivateCardListByCardSeqNo(socd
								.getStartCardSeqNo(), socd.getEndCardSeqNo(),
								socd.getBatchNo());
				// 售卡明细列表
				for (int j = 0; j < ActivateCardList.size(); j++) {
					ac = ActivateCardList.get(j);
					// 添加不重复卡顺序号
					if (!cardSeqNoList.contains(ac.getCardSeqNo())) {
						cardSeqNoList.add(ac.getCardSeqNo());
					}
					hm.put(ac.getCardSeqNo(), ac.getCardNo());// 卡序列号
					batchNoHm.put(ac.getCardSeqNo(), socd.getBatchNo());
				}
			} else {
				// 详细卡列表
				List<CardStock> cardStockList = cardStockDaoImpl
						.getCardStockListBySaleBranchNoAndCardSeqNo(socd
								.getStartCardSeqNo(), socd.getEndCardSeqNo(),
								saleOrder.getSaleBranchNo());
				// 售卡明细列表
				for (int j = 0; j < cardStockList.size(); j++) {
					cs = cardStockList.get(j);
					// 添加不重复卡顺序号
					if (!cardSeqNoList.contains(cs.getCardSeqNo())) {
						cardSeqNoList.add(cs.getCardSeqNo());
					}
					hm.put(cs.getCardSeqNo(), cs.getCardNo());// 卡序列号
					batchNoHm.put(cs.getCardSeqNo(), cs.getBatchNo());
				}
			}
		}
		// if(hm.size()>65536){
		// return null;
		// }
		List<CardStock> returnList = new ArrayList<CardStock>();
		// 循环卡顺序号
		for (String str : cardSeqNoList) {
			cs = new CardStock();
			cs.setBatchNo(batchNoHm.get(str));
			cs.setCardSeqNo(str);
			cs.setCardNo(hm.get(str));
			returnList.add(cs);
		}
		return returnList;
	}
}
